package com.koron.css2.newProjectCenter.impl.inforManag;

import cn.hutool.core.date.DateTime;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.koron.css2.ServerInterface;
import com.koron.css2.newProjectCenter.bean.query.PubUpNoticeQueryBean;
import com.koron.css2.newProjectCenter.mapper.PubUpNoticeMapper;
import com.koron.css2.newProjectCenter.vo.PubUpNoticeListVO;
import com.koron.css2.serviceManage.bean.RequestBean;
import com.koron.css2.serviceManage.bean.UserInfoBean;
import com.koron.css2.serviceManage.utils.JsonUtils;
import com.koron.util.Constant;
import com.koron.util.Tools;
import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.EnvSource;
import org.koron.ebs.mybatis.SessionFactory;
import org.swan.bean.MessageBean;

import java.util.List;

/**
 * 公告
 *
 * @author xusheng
 */
public class PubUpNoticeList implements ServerInterface {
    @Override
    @SuppressWarnings("rawtypes")
    public MessageBean<?> exec(SessionFactory factory, UserInfoBean userInfo, RequestBean req) {
        try {
            // 将入参转换为QueryBean
            PubUpNoticeQueryBean queryBean = JsonUtils.objectToPojo(req.getData(), PubUpNoticeQueryBean.class);

            // 获取Mapper实例
            PubUpNoticeMapper mapper = factory.getMapper(PubUpNoticeMapper.class, EnvSource.DEFAULT);
            if (queryBean.getToDo() != null && queryBean.getToDo() == 2) {
                return saveOrUpdate(mapper, userInfo, queryBean);
            }
            if (queryBean.getToDo() != null && queryBean.getToDo() == 3) {
                return clearMessage(mapper, queryBean);
            }

            // 设置分页参数
            PageHelper.startPage(queryBean.getPage(), queryBean.getPageCount());

            List<PubUpNoticeListVO> list;

            int noticeStatus = Constant.NOTICE_STATUS_KNOWN;
            // 查询所有数据
            if (queryBean.getToDo() != null && queryBean.getToDo() == 1) {
                list = mapper.selectAllList(queryBean);
            }
            // 查询所有新发布的数据（即为未知）
            else {
                list = mapper.selectUnknownList(queryBean, userInfo.getUserInfo().getAcount());
            }
            PageInfo<PubUpNoticeListVO> vos = new PageInfo<>(list);
            // 将查询出来的数据状态更改为已知晓
            List<PubUpNoticeListVO> result = vos.getList();
            // 将result的id收集出来创建一个列表
            result.forEach(item -> {
                if (StringUtils.isEmpty(mapper.getRecordIdByNoticeIdAndAccount(item.getId(), userInfo.getUserInfo().getAcount()))) {
                    mapper.setMsgStatusByIds(Tools.getObjectId(), item.getId(), userInfo.getUserInfo().getAcount(), noticeStatus);
                }
            });
            // 输出分页结果
            MessageBean<PageInfo> info = MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "查询成功", PageInfo.class);
            info.setData(vos);
            return info;
        } catch (Exception e) {
            factory.close(false);
            logger.error("查询失败" + e.getMessage(), e);
            return MessageBean.create(Constant.MESSAGE_INT_FAIL, "查询失败", null);
        }
    }

    private MessageBean<?> clearMessage(PubUpNoticeMapper thisMapper, PubUpNoticeQueryBean queryBean) {
        if (StringUtils.isEmpty(queryBean.getId())) {
            return MessageBean.create(Constant.NOT_NULL, "消息主键不能为空", null);
        }
        MessageBean<Integer> info = MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "修改成功", Integer.class);
        Integer num = thisMapper.clearMessage(queryBean.getId());
        info.setData(num);
        return info;
    }

    private MessageBean<?> saveOrUpdate(PubUpNoticeMapper thisMapper, UserInfoBean userInfo, PubUpNoticeQueryBean queryBean) {
        if (StringUtils.isEmpty(queryBean.getId())) {
            queryBean.setCreateAccount(userInfo.getUserInfo().getAcount());
            queryBean.setCreateTime(new DateTime());
            queryBean.setCreateName(userInfo.getUserInfo().getName());
            queryBean.setId(Tools.getObjectId());
        } else {
            queryBean.setUpdateAccount(userInfo.getUserInfo().getAcount());
            queryBean.setUpdateTime(new DateTime());
            queryBean.setUpdateName(userInfo.getUserInfo().getName());
        }
        int num = thisMapper.updateOrSave(queryBean);

        MessageBean<Integer> info = MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "修改成功", Integer.class);
        info.setData(num);
        return info;
    }

    // // 每天凌晨3点执行清理过期消息的任务
    // @Scheduled(cron = "0 0 3 * * *")
    // public void clearExpiredMessage() {
    //     try (SessionFactory factory = new SessionFactory()) {
    //         // 获取数据库操作映射器
    //         PubUpNoticeMapper mapper = factory.getMapper(PubUpNoticeMapper.class, EnvSource.DEFAULT);
    //
    //         // 获取过期消息的id
    //         List<String> ids = mapper.getExpiredMessageFromNotice();
    //
    //         // 如果存在过期消息，则进行删除操作
    //         if (!ids.isEmpty()) {
    //             // 从notice表中删除过期消息
    //             mapper.clearExpiredMessageFromNotice(ids);
    //             // 从notice_read_record表中删除过期消息
    //             mapper.clearExpiredMessageFromRecord(ids);
    //         }
    //     } catch (Exception e) {
    //         // 记录清理过期消息时发生的错误
    //         logger.error("定时清理过期消息失败", e);
    //     }
    // }
}
